using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using GuruAsp.Store.StoreLib;

namespace GuruAsp.Store.Web
{
	public partial class lostpass : System.Web.UI.Page
	{
		protected string mErrorMsg = "";
		protected UtilityHelper util = null;

		protected void Page_Load(object sender, EventArgs e)
		{
			Response.AppendHeader("content-type", "text/plain");
			Response.Cache.SetCacheability(HttpCacheability.NoCache); //disable caching of this page

			util = new UtilityHelper(new QueryStringParams(Request.QueryString));

			if (Request.Form["cmd"] == "showLostPass")
			{
				plcDetails.Visible = true;
			}
			else if (Request.Form["cmd"] == "sendPass")
			{
				plcDetails.Visible = true;

				string strEmail = Request.Form["email"] + "";
				if (SendPass(strEmail) == true)
				{
					plcSent.Visible = true;
					plcDetails.Visible = false;
				}
			}
		}

		private bool SendPass(string strEmail)
		{
			if (UtilityHelper.IsEmailValidFormat(strEmail) == false)
			{
				ShowError(util.GetSystemMsg(SystemMsg.ValidEmailRequired));
				email.Value = strEmail;
			}
			else
			{
				Member member = new Member("", strEmail);
				if (member.ID < 1)
				{
					ShowError( util.GetSystemMsg(SystemMsg.EmailNotFound));
					email.Value = strEmail;
				}
				else
				{
					// user found, send password
					System.Collections.Stack emails = new System.Collections.Stack();
					//emails.Push(AppSettings.EmailFromEmail); //send email to administrator too
					emails.Push(member.Email);

					string body = "<html><body><div><b>username: </b>" + member.Username + "</div>" +
						"<div><b>password: </b>" + member.Password + "</div>" +
						"<div><a href='" + AppSettings.WebSite + "'>" + AppSettings.WebSite + "</a></div>" +
						"</body></html>";

					EmailsSenderHandler em = new EmailsSenderHandler(
							AppSettings.EmailServer,
							AppSettings.EmailServerPort,
							AppSettings.EmailUsername,
							AppSettings.EmailPassword,
							AppSettings.FromEmail,
							AppSettings.FromName,
							"Your password",
							body,
							emails,
							1,
							true);

					if (em.WaitUntillSent() == false)
					{
						// request can't be processed right now (email can't be sent)
						ShowError("Request can't be processed right now.");
						return false;
					}
					else
					{
						ShowMessage(util.GetSystemMsg(SystemMsg.PasswordSent));
						return true;

					}
				}
			}
			return false;
		}

		private void ShowError(string text)
		{
			mErrorMsg = text;
		}
		private void ShowMessage(string text)
		{
			mErrorMsg = text;
		}

	}
}
